package com.lengxf.milo.executor;

import cn.hutool.core.collection.CollectionUtil;
import com.lengxf.milo.model.ReadResult;
import com.lengxf.milo.node.NodeIdBuilder;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ReadExecutor {


    public static ReadResult read(UaClient client, String identifier) {
        List<ReadResult> resultList = read(client, Collections.singletonList(identifier));
        if (CollectionUtil.isEmpty(resultList)) {
            return ReadResult.badResult(identifier);
        }
        return resultList.get(0);
    }

    public static List<ReadResult> read(UaClient client, List<String> identifierList) {
        List<ReadResult> readResultList = new ArrayList<>();
        try {
            List<NodeId> nodeIdList = identifierList.stream().map(NodeIdBuilder::build).collect(Collectors.toList());
            List<DataValue> dataValueList = client.readValues(10000, TimestampsToReturn.Both, nodeIdList).get();
            for (int i = 0; i < identifierList.size(); i++) {
                String identifier = identifierList.get(i);
                NodeId nodeId = nodeIdList.get(i);
                DataValue dataValue = dataValueList.get(i);
                readResultList.add(new ReadResult(identifier, nodeId, dataValue));
            }
        } catch (Exception e) {
            System.out.println("read exception");
        }
        return readResultList;
    }

}
